import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useWechatStore = defineStore('wechat', () => {
  const isWechatEnv = ref(false)
  const userInfo = ref<any>(null)
  const jsApiList = ref([
    'chooseImage',
    'previewImage',
    'uploadImage',
    'downloadImage',
    'getLocation',
    'openLocation'
  ])

  // 检查是否在微信环境
  const checkWechatEnv = () => {
    const ua = navigator.userAgent.toLowerCase()
    isWechatEnv.value = ua.includes('micromessenger')
    return isWechatEnv.value
  }

  // 初始化微信配置
  const initWechatConfig = async () => {
    if (!checkWechatEnv()) {
      console.log('非微信环境')
      return
    }

    try {
      // 这里应该调用后端接口获取微信配置
      // const config = await getWechatConfig()
      
      // 临时配置，实际使用时需要从后端获取
      if (typeof wx !== 'undefined') {
        wx.config({
          debug: false,
          appId: import.meta.env.VITE_WECHAT_APPID,
          timestamp: Math.floor(Date.now() / 1000),
          nonceStr: 'nonce_str',
          signature: 'signature',
          jsApiList: jsApiList.value
        })

        wx.ready(() => {
          console.log('微信JS-SDK配置成功')
        })

        wx.error((res: any) => {
          console.error('微信JS-SDK配置失败:', res)
        })
      }
    } catch (error) {
      console.error('初始化微信配置失败:', error)
    }
  }

  // 获取用户信息
  const getUserInfo = () => {
    return userInfo.value
  }

  // 设置用户信息
  const setUserInfo = (info: any) => {
    userInfo.value = info
  }

  return {
    isWechatEnv,
    userInfo,
    checkWechatEnv,
    initWechatConfig,
    getUserInfo,
    setUserInfo
  }
}, {
  persist: {
    key: 'wechat-store',
    storage: localStorage,
    paths: ['userInfo']
  }
})